package com.alks.function.service.impl.finance.mtlcosts;

import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.dto.SysUserTokenDTO;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.beanutils.ArrayUtils;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.beanutils.StringUtils;
import com.alks.entity.data.entity.*;
import com.alks.entity.data.enums.CompanyEnum;
import com.alks.entity.data.enums.SlipTypeEnum;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.finance.mtlcosts.FinSuppDutyTtlDto;
import com.alks.function.data.dto.finance.mtlcosts.FinSuppHeadDto;
import com.alks.function.data.dto.finance.mtlcosts.FinSuppMtlDto;
import com.alks.function.data.dto.finance.mtlcosts.SupCfmPrintDto;
import com.alks.function.data.request.finance.mtlcosts.FinSuppHeadRequest;
import com.alks.function.data.vo.simple.DutyPriceVo;
import com.alks.function.mapper.finance.mtlcosts.PcSupplementDutyTtlMapper;
import com.alks.function.mapper.pcfactorywork.PcSupplementDutyMapper;
import com.alks.function.mapper.stockdept.pcfactorystockquery.SD_SQ_PcSupplementDetailMapper;
import com.alks.function.mapper.stockdept.pcfactorystockquery.SD_SQ_PcSupplementHeadMapper;
import com.alks.function.mapper.stockdept.pcfactorystockquery.SD_SQ_PcSupplementMtlMapper;
import com.alks.function.mapper.stockdept.pcfactorystockquery.SD_SQ_SdBomFitSubMapper;
import com.alks.function.service.finance.mtlcosts.IPcSuppCfmService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import jodd.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author MS
 * @since 2024/6/14上午9:50
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class PcSuppCfmServiceImpl extends ServiceImpl<SD_SQ_PcSupplementMtlMapper, PcSupplementMtl> implements IPcSuppCfmService {
    private final SD_SQ_PcSupplementHeadMapper headMapper;
    private final SD_SQ_PcSupplementDetailMapper detailMapper;
    private final SD_SQ_PcSupplementMtlMapper mtlMapper;
    private final PcSupplementDutyMapper dutyMapper;
    private final PcSupplementDutyTtlMapper ttlMapper;
    private final SD_SQ_SdBomFitSubMapper subMapper;


    @Override
    @AutoPageAop
    public ResponseInfo suppHeadQuery(FinSuppHeadRequest request) {
        String companyId = UserIdThread.get().getCompanyId();
        /*处理补料类型*/
        request.setBlFlag(SlipTypeEnum.SlipTypeFind(request.getBlFlag()));
        /*获取数据*/
        List<FinSuppHeadDto> dtos = headMapper.suppHeadQuery(request, companyId);
        Page<FinSuppHeadDto> page = (Page<FinSuppHeadDto>) dtos;
        /*处理补料类型*/
        dtos.forEach(dto -> dto.setBlFlag(SlipTypeEnum.SlipNameFind(dto.getBlFlag())));
        Map<String, Object> map = new HashMap<>(2);
        map.put("dtos", dtos);
        map.put("total", page.getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo suppDetQuery(String slipNo) {
        String companyId = UserIdThread.get().getCompanyId();
        /*补料数据*/
        List<FinSuppMtlDto> mtlDtos = mtlMapper.suppDetQuery(slipNo, companyId);
        /*责任数据*/
        LambdaQueryWrapper<PcSupplementDutyTtl> ttlWrapper = new LambdaQueryWrapper<PcSupplementDutyTtl>()
                .eq(PcSupplementDutyTtl::getSlipNo, slipNo)
                .eq(PcSupplementDutyTtl::getCompanyId, companyId);
        Integer count = ttlMapper.selectCount(ttlWrapper);
        List<FinSuppDutyTtlDto> dutyDtos = new ArrayList<>();
        if (count <= 0) {
            /*未计算金额时展示责任方*/
            dutyDtos = dutyMapper.finSuppDetQuery(slipNo, companyId);
        } else {
            /*计算金额后展示责任方详细数据*/
            List<PcSupplementDutyTtl> ttls = ttlMapper.selectList(ttlWrapper);
            dutyDtos = BeanUtil.copyList(ttls, FinSuppDutyTtlDto.class);
            /*保留两位小数，四舍五入*/
            for (FinSuppDutyTtlDto dto : dutyDtos) {
                dto.setLaborAmt(dcmNoNull(dto.getLaborAmt()).setScale(2, RoundingMode.HALF_UP));
                dto.setAmt(dcmNoNull(dto.getAmt()).setScale(2, RoundingMode.HALF_UP));
                dto.setLaborAmtCut(dcmNoNull(dto.getLaborAmtCut()).setScale(2, RoundingMode.HALF_UP));
                dto.setLaborAmtCut2(dcmNoNull(dto.getLaborAmtCut2()).setScale(2, RoundingMode.HALF_UP));
                dto.setLaborAmtCut3(dcmNoNull(dto.getLaborAmtCut3()).setScale(2, RoundingMode.HALF_UP));
                dto.setLaborAmtStitch(dcmNoNull(dto.getLaborAmtStitch()).setScale(2, RoundingMode.HALF_UP));
                dto.setLaborAmtLast(dcmNoNull(dto.getLaborAmtLast()).setScale(2, RoundingMode.HALF_UP));
            }
        }
        /*封装返回*/
        Map<String, Object> map = new HashMap<>(2);
        map.put("mtlDtos", mtlDtos);
        map.put("dutyDtos", dutyDtos);
        return ResponseInfo.ok(map);
    }

    private static BigDecimal dcmNoNull(BigDecimal num) {
        return num == null ? BigDecimal.ZERO : num;
    }

    @Override
    public ResponseInfo fitSubQuery(String mtlNo) {
        String companyId = UserIdThread.get().getCompanyId();
        /*获取子材料明细1*/
        List<Map<String, Object>> subList = subMapper.finSuppMtlSubFitQuery(mtlNo, companyId);
        List<Map<String, Object>> subs = new ArrayList<>();
        List<Map<String, Object>> subs2 = new ArrayList<>();
        if (ArrayUtils.isNoEmpyt(subList)) {
            subs.add(subList.get(0));
            subs2.add(subList.get(1));
        }
        Map<String, Object> map = new HashMap<>(4);
        /*封装数据*/
        map.put("subs", subs);
        map.put("subs2", subs2);
        return ResponseInfo.ok(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseInfo suppCostComp(String slipNo, Integer type, String dept) {
        String companyId = UserIdThread.get().getCompanyId();
        switch (type) {
            case 1:
                getPrice(slipNo, companyId);
                break;
            case 2:
                mtlTtlCost(slipNo, companyId);
                break;
            case 3:
                laborCost(slipNo, companyId, dept);
                break;
            default:
                break;
        }
        return ResponseInfo.ok();
    }

    /**
     * 取材料单价
     *
     * @param slipNo    补料单号
     * @param companyId 公司ID
     */
    private void getPrice(String slipNo, String companyId) {
        /*如果单价全部不为空则无法计算*/
        LambdaQueryWrapper<PcSupplementMtl> wrapper = new LambdaQueryWrapper<PcSupplementMtl>()
                .eq(PcSupplementMtl::getSlipNo, slipNo)
                .eq(PcSupplementMtl::getCompanyId, companyId)
                .isNull(PcSupplementMtl::getPrice);
        Integer count = mtlMapper.selectCount(wrapper);
        if (count == 0) {
            throw new ServiceErrorException("没有为空的单价");
        }
        mtlMapper.getPrice(slipNo, companyId);
    }

    /**
     * 计算责任金额
     *
     * @param slipNo    单据号
     * @param companyId 公司ID
     */
    private void mtlTtlCost(String slipNo, String companyId) {
        String userName = UserIdThread.get().getUserName();
        /*单价为空则不能修改*/
        LambdaQueryWrapper<PcSupplementMtl> mtlWrapper = new LambdaQueryWrapper<PcSupplementMtl>()
                .eq(PcSupplementMtl::getSlipNo, slipNo)
                .eq(PcSupplementMtl::getCompanyId, companyId);
        List<PcSupplementMtl> mtls = mtlMapper.selectList(mtlWrapper);
        List<PcSupplementMtl> noPriceMtls = Optional.ofNullable(mtls)
                .orElseGet(Collections::emptyList).stream()
                .filter(Objects::nonNull)
                .filter(mtl -> mtl.getPrice() == null)
                .collect(Collectors.toList());
        if (!ArrayUtils.isEmpyt(noPriceMtls)) {
            throw new ServiceErrorException("材料单价不能为空");
        }
        /*删除原本数据*/
        LambdaQueryWrapper<PcSupplementDutyTtl> wrapper = new LambdaQueryWrapper<PcSupplementDutyTtl>()
                .eq(PcSupplementDutyTtl::getSlipNo, slipNo)
                .eq(PcSupplementDutyTtl::getCompanyId, companyId);
        ttlMapper.delete(wrapper);
        /*写入责任金额数据*/
        ttlMapper.mtlTtlCost(slipNo, companyId, userName);
    }

    /**
     * 计算人工费用
     *
     * @param slipNo    单据号
     * @param companyId 公司ID
     * @param dept
     */
    @Transactional(rollbackFor = Exception.class)
    public void laborCost(String slipNo, String companyId, String dept) {
        /*判断是否已计算责任金额*/
        //MS TODO 2025/1/9 : 写的很急很乱 有待优化
        LambdaQueryWrapper<PcSupplementDutyTtl> wrapper = new LambdaQueryWrapper<PcSupplementDutyTtl>()
                .eq(PcSupplementDutyTtl::getCompanyId, companyId)
                .eq(PcSupplementDutyTtl::getSlipNo, slipNo);
        List<PcSupplementDutyTtl> ttlList = ttlMapper.selectList(wrapper);
        if (ArrayUtils.isEmpyt(ttlList)) {
            throw new ServiceErrorException("无责任金额数据，请先【计算责任金额】");
        }
        /*获取总的责任方责任占比*/
        BigDecimal totalQty = ttlList.stream()
                .map(PcSupplementDutyTtl::getDutyQty)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal totalProportion = BigDecimal.ZERO;
        int size = ttlList.size();
        for (int i = 0; i < size; i++) {
            PcSupplementDutyTtl item = ttlList.get(i);
            BigDecimal dutyQty = item.getDutyQty();
            if (dutyQty == null || totalQty.compareTo(BigDecimal.ZERO) == 0) {
                /*暂时将责任比例存放在laborAmtStitch中*/
                item.setLaborAmtStitch(BigDecimal.ZERO);
                continue;
            }
            BigDecimal proportion;
            if (i == size - 1) {
                proportion = BigDecimal.ONE.subtract(totalProportion);
            } else {
                proportion = dutyQty.divide(totalQty, 8, RoundingMode.HALF_UP);
                totalProportion = totalProportion.add(proportion).setScale(8, RoundingMode.HALF_UP);
            }
            proportion = proportion.setScale(6, RoundingMode.HALF_UP);
            item.setLaborAmtCut(proportion);
        }
        /*获取所属责任部门*/
        LambdaUpdateWrapper<PcSupplementHead> headWrapper = new LambdaUpdateWrapper<PcSupplementHead>()
                .eq(PcSupplementHead::getSlipNo, slipNo)
                .eq(PcSupplementHead::getCompanyId, companyId);
        PcSupplementHead head = headMapper.selectOne(headWrapper);
        if (StringUtils.isBlank(dept)) {
            if (head.getDutyDeptName().contains("仓")) {
                dept = "仓储";
            } else if (head.getDutyDeptName().contains("冲")) {
                dept = "冲裁";
            } else if (head.getDutyDeptName().contains("手")) {
                dept = "手工";
            } else if (head.getDutyDeptName().contains("外")) {
                dept = "外发";
            } else if (head.getDutyDeptName().contains("针")) {
                dept = "针车";
            } else if (head.getDutyDeptName().contains("成")) {
                dept = "成型";
            } else {
                throw new ServiceErrorException("部门类别无法识别,请手动选择计算起始节点");
            }
        }
        /*分别获取各工艺人工费用*/
        List<PcSupplementDetail> totalDetailList = detailMapper.getSpLotTotal(slipNo, companyId);
        List<PcSupplementDetail> percentDetailList = detailMapper.getSpMtlPercent(ttlList, companyId);
        /*定义变量*/
        BigDecimal lastAmt = BigDecimal.ZERO;
        List<DutyPriceVo> cut3List = new ArrayList<>();
        List<DutyPriceVo> cut2List = new ArrayList<>();
        switch (dept) {
            case "成型":
                /*获取成型费用*/
                lastAmt = totalDetailList.stream()
                        .collect(Collectors.groupingBy(
                                PcSupplementDetail::getLotNo,
                                Collectors.maxBy(Comparator.comparing(a -> a.getTotalQty() == null ? 0 : a.getTotalQty()))
                        ))
                        .values()
                        .stream()
                        .filter(Optional::isPresent)
                        .map(Optional::get)
                        .map(a -> BigDecimal.valueOf(a.getTotalQty()).multiply(BigDecimal.valueOf(12)))
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
            case "针车":
                /*获取针车费用*/
                List<BigDecimal> switchAmtList = detailMapper.getSwitchPrice(totalDetailList, companyId);
                if (ArrayUtils.isEmpyt(switchAmtList)) {
                    throw new ServiceErrorException("针车人工费用未定义");
                }
                BigDecimal switchAmt = switchAmtList.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal finalLastAmt = lastAmt;
                ttlList.forEach(ttl -> {
                    ttl.setLaborAmtLast(ttl.getLaborAmtCut().multiply(finalLastAmt));
                    ttl.setLaborAmtStitch(ttl.getLaborAmtCut().multiply(switchAmt));
                });
            case "外发":
                /*判断是否有外发需求*/
                String outLot = detailMapper.checkOut(slipNo, companyId);
                if (StringUtil.isNotBlank(outLot)) {
                    /*获取外发费用*/
                    cut3List = detailMapper.getCut3Price(percentDetailList, companyId);
                    if (ArrayUtils.isEmpyt(cut3List)) {
                        throw new ServiceErrorException("外发费用未定义");
                    }
                }
            case "手工":
                String lotNo2 = detailMapper.checkCut2(slipNo, companyId);
                if (StringUtil.isBlank(lotNo2)) {
                    throw new ServiceErrorException("手工费用未定义");
                }
                /*获取手工费用*/
                cut2List = detailMapper.getCut2Price(percentDetailList, companyId);
            case "冲裁":
                /*获取冲裁费用*/
                String lotNo = detailMapper.checkCut(slipNo, companyId);
                if (StringUtil.isBlank(lotNo)) {
                    throw new ServiceErrorException("冲裁费用未定义");
                }
                List<DutyPriceVo> cutList = detailMapper.getCutPrice(ttlList, companyId);
                for (PcSupplementDutyTtl ttl : ttlList) {
                    /*写入手工单价*/
                    BigDecimal cutAmt = cutList.stream()
                            .filter(cut -> ttl.getDutyName().equals(cut.getDutyName()))
                            .map(DutyPriceVo::getPrice)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    ttl.setLaborAmtCut(cutAmt);
                    /*写入手工单价*/
                    BigDecimal cut2Amt = cut2List.stream()
                            .filter(cut2 -> ttl.getDutyName().equals(cut2.getDutyName()))
                            .map(DutyPriceVo::getPrice)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    ttl.setLaborAmtCut2(cut2Amt);
                    /*写入外协单价*/
                    BigDecimal cut3Amt = cut3List.stream()
                            .filter(cut3 -> ttl.getDutyName().equals(cut3.getDutyName()))
                            .map(DutyPriceVo::getPrice)
                            .filter(Objects::nonNull)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    ttl.setLaborAmtCut3(cut3Amt);
                    /*计算总金额*/
                    ttl.setLaborAmt(ttl.getLaborAmtCut()
                            .add(ttl.getLaborAmtCut2())
                            .add(ttl.getLaborAmtCut3())
                            .add(ttl.getLaborAmtStitch())
                            .add(ttl.getLaborAmtLast())
                            .setScale(2, RoundingMode.HALF_UP));
                    ttl.setAmt(ttl.getLaborAmt().add(ttl.getDutyAmt()).setScale(2, RoundingMode.HALF_UP));
                }
            default:
                break;
        }
        /*数据更新*/
        ttlMapper.delete(wrapper);
        for (PcSupplementDutyTtl ttl : ttlList) {
            ttlMapper.insert(ttl);
        }
        /*更新主表数据*/
        BigDecimal laborAmt = ttlList.stream()
                .map(PcSupplementDutyTtl::getLaborAmt)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        headWrapper
                .set(PcSupplementHead::getLaborFee, laborAmt);
        headMapper.update(null, headWrapper);
    }

    private BigDecimal noNull(BigDecimal num) {
        return num == null ? BigDecimal.ZERO : num;
    }

    @Override
    public ResponseInfo suppFinalCheck(List<String> slipNos, Integer type) {
        SysUserTokenDTO tokenDTO = UserIdThread.get();
        String userName = tokenDTO.getUserName();
        String companyId = tokenDTO.getCompanyId();
        int check = 1;
        int uncheck = 0;
        /*单价为空则不能修改*/
        LambdaQueryWrapper<PcSupplementMtl> mtlWrapper = new LambdaQueryWrapper<PcSupplementMtl>()
                .in(PcSupplementMtl::getSlipNo, slipNos)
                .eq(PcSupplementMtl::getCompanyId, companyId);
        List<PcSupplementMtl> mtls = mtlMapper.selectList(mtlWrapper);
        Set<String> errSlipNos = mtls.stream().filter(mtl -> mtl.getPrice() == null)
                .map(PcSupplementMtl::getSlipNo).collect(Collectors.toSet());
        if (!ArrayUtils.isEmpyt(errSlipNos)) {
            String errSlipNo = new ArrayList<>(errSlipNos).get(0);
            return ResponseInfo.error("包括【" + errSlipNo + "】在内的" + errSlipNos.size() + "个单据存在物料单价为空的情况，不能修改");
        }
        /*判断是否已审核*/
        LambdaUpdateWrapper<PcSupplementHead> wrapper = new LambdaUpdateWrapper<PcSupplementHead>()
                .in(PcSupplementHead::getSlipNo, slipNos)
                .eq(PcSupplementHead::getCompanyId, companyId);
        List<PcSupplementHead> heads = headMapper.selectList(wrapper);
        List<PcSupplementHead> noFinanceHeads = heads.stream()
                .filter(head -> StringUtil.isBlank(head.getFinanceFlag()))
                .collect(Collectors.toList());
        if (!ArrayUtils.isEmpyt(noFinanceHeads)) {
            return ResponseInfo.error("包括【" + noFinanceHeads.get(0).getSlipNo() + "】在内的" + noFinanceHeads.size() + "个单据未审核，不能修改");
        }
        List<String> findSlipNos = heads.stream().map(PcSupplementHead::getSlipNo).collect(Collectors.toList());
        List<String> miss = ArrayUtils.findMiss(findSlipNos, slipNos);
        if (!ArrayUtils.isEmpyt(miss)) {
            log.warn("\n异常接口：suppFinalCheck\n异常原因：传入数据在数据库中不存在\n详情：未在【PC_SUPPLEMENT_HEAD】中找到SLIP_NO：{}", miss);
            throw new ServiceErrorException("包括【" + miss.get(0) + "】在内的" + miss.size() + "个单据未找到，不能修改");
        }
        /*判断是否重复操作*/
        if (type.equals(check)) {
            List<PcSupplementHead> checkHead = heads.stream()
                    .filter(head -> "Y".equals(head.getFinanceFlag2()))
                    .collect(Collectors.toList());
            if (!ArrayUtils.isEmpyt(checkHead)) {
                throw new ServiceErrorException("包括【" + checkHead.get(0) + "】在内的" + checkHead.size() + "个单据已审核，不能重复审核");
            }
        } else if (type.equals(uncheck)) {
            List<PcSupplementHead> checkHead = heads.stream()
                    .filter(head -> !"Y".equals(head.getFinanceFlag2()))
                    .collect(Collectors.toList());
            if (!ArrayUtils.isEmpyt(checkHead)) {
                throw new ServiceErrorException("包括【" + checkHead.get(0) + "】在内的" + checkHead.size() + "个单据未审核，不能重复取消审核");
            }
        }
        /*更新数据*/
        if (type.equals(uncheck)) {
            wrapper.set(PcSupplementHead::getFinanceFlag2, null)
                    .set(PcSupplementHead::getFinanceUser2, null)
                    .set(PcSupplementHead::getFinanceDate2, null);
        } else if (type.equals(check)) {
            wrapper.set(PcSupplementHead::getFinanceFlag2, "Y")
                    .set(PcSupplementHead::getFinanceDate2, LocalDate.now())
                    .set(PcSupplementHead::getFinanceUser2, userName);
        }
        headMapper.update(null, wrapper);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo suppDetPriceUpdate(String slipNo, String mtlNo, BigDecimal price) {
        String companyId = UserIdThread.get().getCompanyId();
        String fill = "填充单价";
        /*判断入参健壮性*/
        if (price != null && price.compareTo(BigDecimal.ZERO) < 0) {
            return ResponseInfo.error("单价不能小于0");
        }
        /*单价修改*/
        LambdaUpdateWrapper<PcSupplementMtl> wrapper = new LambdaUpdateWrapper<PcSupplementMtl>()
                .eq(PcSupplementMtl::getSlipNo, slipNo)
                .eq(!fill.equals(mtlNo), PcSupplementMtl::getMtlNo, mtlNo)
                .eq(PcSupplementMtl::getCompanyId, companyId)
                .set(PcSupplementMtl::getPrice, price);
        /*修改单价*/
        mtlMapper.update(null, wrapper);
        return ResponseInfo.ok();
    }

    @Override
    public ResponseInfo suppDutyPriceUpdate(String slipNo, String dutyName, BigDecimal freeAmt) {
        String companyId = UserIdThread.get().getCompanyId();
        /*修改免扣金额*/
        LambdaUpdateWrapper<PcSupplementDutyTtl> wrapper = new LambdaUpdateWrapper<PcSupplementDutyTtl>()
                .eq(PcSupplementDutyTtl::getSlipNo, slipNo)
                .eq(PcSupplementDutyTtl::getDutyName, dutyName)
                .eq(PcSupplementDutyTtl::getCompanyId, companyId);
        List<PcSupplementDutyTtl> ttls = ttlMapper.selectList(wrapper);
        if (ArrayUtils.isEmpyt(ttls)) {
            log.warn("\n异常接口：suppDutyPriceUpdate\n异常原因：未在数据库中找到数据\n详情：未在【PC_SUPPLEMENT_DUTY_TTL】中找到slipNo为{}，dutyName为{}的数据", slipNo, dutyName);
        }
        wrapper.set(PcSupplementDutyTtl::getFreeAmt, freeAmt);
        ttlMapper.update(null, wrapper);
        return ResponseInfo.ok();
    }

    @Override
    public void suppRekUpdate(String slipNo, String cwRek) {
        String companyId = UserIdThread.get().getCompanyId();
        /*数据检测*/
        LambdaUpdateWrapper<PcSupplementHead> wrapper = new LambdaUpdateWrapper<PcSupplementHead>()
                .eq(PcSupplementHead::getCompanyId, companyId)
                .eq(PcSupplementHead::getSlipNo, slipNo);
        Integer count = headMapper.selectCount(wrapper);
        if (count == 0) {
            throw new ServiceErrorException("订单号不存在");
        }
        if (count > 1) {
            throw new ServiceErrorException("订单号不唯一");
        }
        /*修改备注*/
        wrapper.set(PcSupplementHead::getCwRek, cwRek);
        headMapper.update(null, wrapper);
    }

    @Override
    public SupCfmPrintDto cfmPrint(String slipNo, String lotNo) {
        String companyId = UserIdThread.get().getCompanyId();
        /*获取表头数据*/
        SupCfmPrintDto dto = headMapper.cfmPrintHeadQuery(slipNo, lotNo, companyId);
        if (dto == null || StringUtils.isBlank(dto.getSlipNo())) {
            throw new ServiceErrorException("订单不存在");
        }
        /*数据补正*/
        dto.setCompanyId(CompanyEnum.getCompanyName(companyId));
        dto.setBlFlag(SlipTypeEnum.SlipNameFind(dto.getBlFlag()));
        /*补料部位数据*/
        List<String> part = detailMapper.cfmPrintPartQuery(slipNo, lotNo, companyId);
        dto.setPart(part);
        /*获取材料部分数据*/
        List<PcSupplementMtl> mtlList = mtlMapper.cfmPrintMtlQuery(slipNo, companyId);
        dto.setMtlList(mtlList);
        /*获取责任部分数据*/
        List<PcSupplementDutyTtl> dutyList = ttlMapper.cfmPrintDutyQuery(slipNo, companyId);
        dto.setDutyList(dutyList);
        return dto;
    }


}
